<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title>导航栏滑动门效果</title>
		<style type="text/css">
			.nav-wrap {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 40px;
				position: relative;
			}
			.item {
				width: 20%;
				text-align: center;
			}
			.active {
				color: #f45656;
			}
			.activeTip {
				position: absolute;
				bottom: 0;
				left: 0;
				width: 30px;
				height: 2px;
				margin-left: 15px;
				background-color: #f45656;
				transition: all .5s;
			}
		</style>
	</head>
	<body>
		<div class="nav-wrap">
			<div class="item active">首页</div>
			<div class="item">类目</div>
			<div class="item">类目</div>
			<div class="item">类目</div>
			<div class="item">类目</div>
			<div class="activeTip"></div>
		</div>
		<script type="text/javascript">
			var navItems  = document.querySelectorAll(".item");
			var activeTip = document.querySelector(".activeTip");
			var boxWidth  = document.querySelector(".nav-wrap").clientWidth;

			// 设置动画
			var setActive = function(index, ele) {
				ele.ontouchstart = function() {
					// 滑动门效果
					activeTip.style.left = (index * boxWidth * .2) + 'px';
					
					// 将active类全部移除
					for (var i = 0; i < navItems.length; i++) {
						navItems[i].setAttribute("class", "item");
					}
					// 当前项添加active类
					ele.setAttribute("class", "item active");
				}
			}
			
			// 为每项添加点击事件
			for (var i = 0; i < navItems.length; i++) {
				setActive(i, navItems[i])
			}	
		</script>
	</body>
</html>
